import axios from 'axios';

// 创建API实例
const service = axios.create({
  baseURL: '/api',
  timeout: 5000
});

// 请求拦截器（添加认证信息）
service.interceptors.request.use(
  config => {
    // 添加token等认证信息
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器（统一处理错误）
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !== 200) {
      console.error(res.message || '请求失败');
      return Promise.reject(new Error(res.message || '请求失败'));
    }
    return res.data; // 返回业务数据
  },
  error => {
    console.log('err' + error);
    return Promise.reject(error);
  }
);

// 套餐管理API
export const packageApi = {
  getList: (params:any) => service.get('/packages', { params }),
  create: (data:any) => service.post('/packages', data),
  update: (id:any, data:any) => service.put(`/packages/${id}`, data),
  delete: (id:any) => service.delete(`/packages/${id}`),
  toggleStatus: (id:any, status:any) => service.patch(`/packages/${id}/status`, { status }),
};

// 项目管理API
export const itemApi = {
  getList: (params:any) => service.get('/items', { params }),
  create: (data:any) => service.post('/items', data),
  update: (id:any, data:any) => service.put(`/items/${id}`, data),
  delete: (id:any) => service.delete(`/items/${id}`),
  toggleStatus: (id:any, status:any) => service.patch(`/items/${id}/status`, { status }),
};

// 类型管理API（修复参数问题）
export const typeApi = {
  getList: (params:any) => service.get('/types', { params }),
  create: (data:any) => service.post('/types', data),
  update: (id:any, data:any) => service.put(`/types/${id}`, data),
  delete: (id:any) => service.delete(`/types/${id}`),
  // 修复：添加id参数，正确调用patch方法
  toggleStatus: (id:any, status:any) => service.patch(`/types/${id}/status`, { status }),
};